//
//  AppDelegate.m
//  SlothSecondProj
//
//  Created by 焱 孙 on 14-1-21.
//  Copyright (c) 2014年 visionet. All rights reserved.
//

#import "AppDelegate.h"
#import "ChatCountDao.h"
#import "APService.h"
#import "UIImage+UIImageScale.h"
#import "CustomNavigationController.h"
#import "UserVo.h"
#import "LanguageManage.h"
#import "SocketIOManage.h"
#import "SessionDetailViewController.h"
#import "ServerURL.h"
#import "NotifyListViewController.h"
#import "TicketDetailViewController.h"

#define kJPushNotify    1001
#define kJPushChat      1002
#define kJPushGroupChat      1003
#define kJPushBroadcast     1004
#define kWSNotify    1005

#define kJPushTicket     1006       //工单转移或分配

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    self.bRespondsToViewWillAppear = YES;
    
    self.bChatJPUSH = NO;
    self.nStartModal = kNormalStart;
    
    //init global value
    [Common initGlobalValue];
    _currentPageName = OtherPage;
    
    //初始化表情数据
    [self initFaceData];
    
    self.aryAlertView = [[NSMutableArray alloc]init];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //DB setting(在任何网络之前设置)
    [ServerURL initServerURL];
    
    //初始化语言设置
    [LanguageManage initLanguageSetting];
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        self.loginViewController = [[LoginViewController alloc] init];
        CustomNavigationController *loginNavController = [[CustomNavigationController alloc] initWithRootViewController:_loginViewController];
        loginNavController.navigationBarHidden = YES;
        _loginViewController.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.window.rootViewController = loginNavController;
    }
    
    [self.window makeKeyAndVisible];
    
    //init JPush
    [self initJPushWithOptions:launchOptions];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveWebSocketPush:) name:WS_RECEIVE_MSG object:nil];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // Required
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error
{
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //处理推送信息
    [self networkDidReceiveMessage:userInfo];
    
    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    //JPUSH
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
//    //进入后台模式，断开WebSocket连接
//    SocketIOManage *socketIOManage = [SocketIOManage sharedSocketIOManage];
//    if(socketIOManage != nil)
//    {
//        [socketIOManage disconnectWebSocket];
//    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    //JPUSH
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    _nStartModal = kEnterForeground;
    
//    //进入前台模式，打开WebSocket连接
//    SocketIOManage *socketIOManage = [SocketIOManage sharedSocketIOManage];
//    if(socketIOManage != nil)
//    {
//        [socketIOManage connectWebSocket:NO];
//    }
    
    //为了保持session,再次请求一个接口（只有登录成功才会去尝试，如果session超时则框架内部重新登录，如果没有超时则会延长session时间）
    [BusinessCommon keepSessionAction:nil];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler
{
    //处理推送信息
    [self networkDidReceiveMessage:userInfo];
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

+ (AppDelegate*)getSlothAppDelegate
{
	return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}

//////////////////////////////////////////////////////////////////////
-(void)initJPushWithOptions:(NSDictionary *)launchOptions
{
    //判断程序是不是由推送服务完成的
    if (launchOptions)
    {
        NSDictionary* pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (pushNotificationKey)
        {
            //点击系统推送通知启动
            _nStartModal = kNotifyStart;
        }
        else
        {
            //点击应用图标启动
            _nStartModal = kNormalStart;
        }
    }
    else
    {
        //点击应用图标启动
        _nStartModal = kNormalStart;
    }
    
    // Required
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    else
    {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
    }
#else
    //categories 必须为nil
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
#endif
    // Required
    [APService setupWithOption:launchOptions];
}

- (void)networkDidReceiveMessage:(NSDictionary *)userInfo
{
    self.dicJPushUserInfo = userInfo;
    if ([Common getCurrentUserVo].strUserID.length == 0)
    {
        //当没有设置MemberID, 默认为点击系统推送通知启动（退出登录，再登录过程）
        _nStartModal = kNotifyStart;
    }
    [self tackleJPUSHMessage];
}

-(void)clearOtherAlertView
{
    if(_aryAlertView.count == 0 )
    {
        return;
    }
    
    for (NSInteger i=(_aryAlertView.count-1); i>=0; i--)
    {
        UIAlertView *temp = (UIAlertView *)[_aryAlertView objectAtIndex:i];
        [temp dismissWithClickedButtonIndex:0 animated:NO];
        [_aryAlertView removeObjectAtIndex:i];
    }
}

-(void)saveUnseeChatNum:(NSDictionary*)dicData
{
    self.bChatJPUSH = YES;
    
    int nNotifyType = -1;
    id objType = [dicData valueForKey:@"type"];
    if (objType != nil && objType != [NSNull null])
    {
        nNotifyType = [objType intValue];
    }
    
    if(nNotifyType == 1)
    {
        //客服与客户:1
        id talkId = [dicData valueForKey:@"talkId"];
        id talkStatus = [dicData valueForKey:@"status"];
        if (talkId != nil && talkId != [NSNull null] && talkStatus != nil && talkStatus != [NSNull null])
        {
            NSString *strKey = [NSString stringWithFormat:@"session_%@",[talkId stringValue]];
            NSString *strStatus = [ChatCountDao getSessionKeyByStatus:[talkStatus integerValue]];
            [ChatCountDao addOneUnseenChatNumByKey:strKey status:strStatus];
        }
    }
}

//推送提醒相关//////////////////////////////////////////////////////////
//处理JPUSH
-(void)tackleJPUSHMessage
{
    //clear badge number
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    //使用APNS的格式（不使用JPUSH格式,没有title字段），{aps:{alert:"test";sound:"default;};ct:0;type:0;uid:2;}
    if(self.dicJPushUserInfo != nil)
    {
        NSDictionary *dicAPS = [self.dicJPushUserInfo valueForKey:@"aps"];
        NSString *content = [dicAPS valueForKey:@"alert"];
        DLog(@"JPUSH:%@",self.dicJPushUserInfo);
        
        //获取推送类型
        id type = [self.dicJPushUserInfo valueForKey:@"type"];
        if (type == [NSNull null] || [type isKindOfClass:[NSNumber class]])
        {
            return;
        }
        
        [self clearOtherAlertView];
        NSString *strNotifyType = [Common checkStrValue:[self.dicJPushUserInfo valueForKey:@"type"]];
        if([strNotifyType isEqualToString:@"repair"])
        {
            //工单分配或转交，弹一个提示框
            self.strTicketID = [Common checkStrValue:[self.dicJPushUserInfo valueForKey:@"serviceSheetNo"]];
            UIAlertView *alertViewTemp =[[UIAlertView alloc] initWithTitle:@"有新工单" message:content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查看",nil];
            alertViewTemp.tag = kJPushTicket;
            [alertViewTemp show];
            [self.aryAlertView addObject:alertViewTemp];
            
            //刷新列表
            [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateTicketList" object:nil];
        }
        else
        {
            //公告，直接进入公告列表
            self.strTicketID = nil;
            UIAlertView *alertViewTemp =[[UIAlertView alloc] initWithTitle:@"有新消息" message:content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查看",nil];
            alertViewTemp.tag = kJPushNotify;
            [alertViewTemp show];
            [self.aryAlertView addObject:alertViewTemp];
        }
        
//        //客服与客户:1
//        if (nNotifyType == 1)
//        {
//            //a:存储未查看的聊天数
//            [self saveUnseeChatNum:self.dicJPushUserInfo];
//            
//            //b:刷新或者跳转操作【三种状态(kInAPP,kEnterForeground,kNormalStart)】
//            if (self.currentPageName == SessionListPage)
//            {
//                //处于聊天人列表界面
//                [[NSNotificationCenter defaultCenter] postNotificationName:JPUSH_REFRESH_CHATLIST object:self.dicJPushUserInfo];
//            }
//            else if (self.currentPageName == SessionContentPage)
//            {
//                //处于聊天界面
//                [[NSNotificationCenter defaultCenter] postNotificationName:JPUSH_REFRESH_CHATCONTENT object:self.dicJPushUserInfo];
//            }
//            else
//            {
//                //other page
//            }
//            _nStartModal = kInAPP;
//            
//            //更新左边菜单顶部提醒数字
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateChatUnreadAllNum" object:nil];
//        }
    }
}

//UIActionSheet delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == kJPushTicket)
    {
        if (buttonIndex==1)
        {
            //维修单推送，查看消息
            if(self.strTicketID != nil)
            {
                TicketVo *ticketVo = [[TicketVo alloc]init];
                ticketVo.strID = self.strTicketID;
                
                TicketDetailViewController *ticketDetailViewController = [[TicketDetailViewController alloc] init];
                ticketDetailViewController.m_ticketVo = ticketVo;
                ticketDetailViewController.refreshTicketBlock = ^(){};
                ticketDetailViewController.ticketDetailType = TicketDetailModifyType;
                [self.loginViewController.navigationController pushViewController:ticketDetailViewController animated:YES];
            }
        }
    }
    else if(alertView.tag == kJPushNotify)
    {
        if (buttonIndex==1)
        {
            //公告推送，查看消息
            NotifyListViewController *notifyListViewController = [[UIStoryboard storyboardWithName:@"NotifyModule" bundle:nil]instantiateViewControllerWithIdentifier:@"NotifyListViewController"];
            notifyListViewController.notifyListViewType = NotifyListPushType;
            [self.loginViewController.navigationController pushViewController:notifyListViewController animated:YES];
        }
    }
}

//初始化表情数据
-(void)initFaceData
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"SlothFace" ofType:@"plist"];
    self.aryFace  = [[NSArray alloc] initWithContentsOfFile:path];
}

//收到WebSocket推送(弹出提示)
- (void)receiveWebSocketPush:(NSNotification*)notifaction
{
    self.chatObjectVo = (ChatObjectVo*)[notifaction object];

    //确定已经登录并且处于其他页面
    if([Common getCurrentUserVo] != nil && self.currentPageName != SessionContentPage)
    {
        //振动提示
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        
        //close other UIAlertView
        [self clearOtherAlertView];
        
        UIAlertView *alertViewTemp =[[UIAlertView alloc] initWithTitle:self.chatObjectVo.strCustomerNickName message:self.chatObjectVo.strLastChatCon delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查看",nil];
        alertViewTemp.tag = kWSNotify;
        [alertViewTemp show];
        [self.aryAlertView addObject:alertViewTemp];
    }
}

@end
